<template>
    <div><!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table :data="roleList" stripe border>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['tagmiddle', 'tbtop',idx1 === scope.row.children.length - 1 ? 'tbbottom' : '']" v-for="(item, idx1) in scope.row.children" :key="item.id">
            <el-col :span="6">
              <el-tag closable @close="deleteById(scope.row, item.id)">{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="18">
              <el-row :class="['tagmiddle', idx2 === item.children.length - 1 ? '' : 'tbbottom']" v-for="(item2, idx2) in item.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @close="deleteById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag v-for="(item3) in item2.children" :key="item3.id" @close="deleteById(scope.row, item3.id)" type="warning" closable>{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialogRole(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRole(scope.row.id)">删除</el-button>
          <el-button size="mini" type="warning" icon="el-icon-setting" @click="allotRightsDialog(scope.row)">角色分配</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加角色对话框-->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog()">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRloe()">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑角色对话框-->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog()">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="allotRightsDialogVisible" width="50%" @close="closeAllotRightsDialog()">
      <el-tree show-checkbox :props="rightsProps" node-key="id"
      :data="rightsList" default-expand-all :default-checked-keys="rightIds"
      ref="treeRefs"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRightsToRole()">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      // 添加相关操作 ------ 开始
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addDialogVisible: false,
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
        ]
      },
      // 添加相关操作 ------- 结束
      // 修改内容 -------开始
      editForm: {},
      editDialogVisible: false,
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限对话框显示与隐藏
      allotRightsDialogVisible: false,
      // 分配权限数据列表
      rightsList: [],
      // 树形
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 角色已有的权限
      rightIds: [],
      // 记录对应的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表信息
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.roleList = res.data
      console.log(res)
    },
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色
    addRloe () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        // 关闭对话框
        this.addDialogVisible = false
        // 添加成功
        this.$message.success('添加角色成功')
        // 刷新表格
        this.getRolesList()
        console.log(res)
      })
    },
    // 打开编辑对话框
    async editDialogRole (id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editDialogVisible = true
      this.editForm = res.data
    },
    // 修改角色
    async editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        console.log(this.editForm)
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败')
        }
        this.editDialogVisible = false
        this.$message.success('修改角色信息成功')
        this.getRolesList()
      })
    },
    // delete
    async delRole (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { return err })
      if (confirmRes !== 'confirm') {
        return this.$message.warning('取消了删除操作')
      }
      // 删除用户
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 提示删除成功
      this.$message.success('删除成功')
      // 刷新表格
      this.getRolesList()
    },
    // 删除权限
    async deleteById (row, id) {
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { return err })
      if (confirmRes !== 'confirm') {
        return this.$message.warning('取消了删除操作')
      }
      // 删除对应的权限 roles/:id/rights/:rightId
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      row.children = res.data
    },
    // 分配权限
    async allotRightsDialog (role) {
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      this.rightIds = []
      this.roleId = role.id
      this.getDefaultRights(role, this.rightIds)
      console.log(this.rightIds)
      this.allotRightsDialogVisible = true
    },
    // 关闭分配权限对话框事件
    closeAllotRightsDialog () {},
    // 默认选中该角色已经拥有的权限
    getDefaultRights (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefaultRights(item, arr)
      })
    },
    // 分配权限到角色
    async allotRightsToRole () {
      // 获取所有选中的
      const idsStr = [...this.$refs.treeRefs.getCheckedKeys(),
        ...this.$refs.treeRefs.getHalfCheckedKeys()].join(',')
      console.log(idsStr)
      // 发送请求设置权限给角色
      // 获取对应的角色
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idsStr })
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败')
      }
      // 提示操作成功
      this.$message.success('更新权限成功')
      // 刷新列表
      this.getRolesList()
      // 关闭对话框
      this.allotRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.tbtop {
  border-top: 1px solid #eee
}
.tbbottom {
  border-bottom: 1px solid #eee
}
.tagmiddle {
  display: flex;
  align-items: center;
}
</style>
